<?php
declare(strict_types=1);

namespace app\logic\api\admin\general;

use app\logic\api\ApiBaseLogic;
use app\model\api\admin\general\RequestLog;


class RequestLogLogic extends ApiBaseLogic
{
    public function __construct()
    {
        $this->model = new RequestLog();
    }

    public function record($request = null, $response = null)
    {
        if ($response) {
            try {
                $response_data = $response->getData();
            } catch (\Throwable $th) {
                trace('request_log_error: ' . json_encode($th->getMessage()));
                $response_data = std_result(-1, '无response数据');
            }
        }

        empty($request) && $request = request();
        $content = $request->param('', null, 'trim,strip_tags,htmlspecialchars');
        // 其他敏感信息也屏蔽
        $content = desensitization($content);

        $data_log = [
            'user_id' => $request->x_token_user['id'] ?? 0,
            'from' => $request->x_token_user['from'] ?? 0,
            'user_name' => $request->x_token_user['username'] ?? '',
            'url' => substr($request->url(), 0, 512),
            'route' => $request->rule()->getRoute(),
            'method' => $request->method(),
            'content' => !is_scalar($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content,
            'ip' => $request->ip(),
            'user_agent' => substr($request->server('HTTP_USER_AGENT'), 0, 255),
            'response_code' => $response_data['code'] ?? '',
            'response_msg' => $response_data['msg'] ?? '',
        ];
        $log = RequestLog::create($data_log);

        return $log->id;
    }
}
